<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择优惠类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="促销活动说明" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入促销活动说明"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="满减条件" prop="condition">
        <el-input
          v-model="queryParams.condition"
          placeholder="请输入满减条件"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="满减额度" prop="reduction">
        <el-input
          v-model="queryParams.reduction"
          placeholder="请输入满减额度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="秒杀价格" prop="seckillPrice">
        <el-input
          v-model="queryParams.seckillPrice"
          placeholder="请输入秒杀价格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="满额送券" prop="couponId">
        <el-select v-model="queryParams.couponId" placeholder="请选择满额送券" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="选择商品" prop="targets">
        <el-input
          v-model="queryParams.targets"
          placeholder="商品绑定"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新增时间" prop="gmtCreate">
        <el-date-picker clearable size="small"
          v-model="queryParams.gmtCreate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择新增时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="gmtUpdate">
        <el-date-picker clearable size="small"
          v-model="queryParams.gmtUpdate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['youxuan:preferential:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['youxuan:preferential:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['youxuan:preferential:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['youxuan:preferential:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="preferentialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="优惠类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="促销活动说明" align="center" prop="description" />
      <el-table-column label="满减条件" align="center" prop="condition" />
      <el-table-column label="排序" align="center" prop="order" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="满减额度" align="center" prop="reduction" />
      <el-table-column label="秒杀价格" align="center" prop="seckillPrice" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="满额送券券" align="center" prop="couponId" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="新增时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['youxuan:preferential:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['youxuan:preferential:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠类型" @change="changeType($event)">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!show_0" label="促销活动说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入促销活动说明" />
        </el-form-item>
        <el-form-item  label="排序" prop="order">
          <el-input v-model="form.order" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="parseInt(dict.dictValue)">{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!show_0&&show_1&&!show_3" label="满减条件" prop="condition">
          <el-input v-model="form.condition" placeholder="请输入满减条件" />
        </el-form-item>
        <el-form-item v-if="!show_0&&!show_3" label="满减额度" prop="reduction">
          <el-input v-model="form.reduction" placeholder="请输入满减额度" />
        </el-form-item>
        <el-form-item v-if="!show_0&&show_3" label="秒杀价格" prop="seckillPrice">
          <el-input v-model="form.seckillPrice" placeholder="请输入秒杀价格" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="!show_0&&show_2&&!show_3" label="满额送券券" prop="couponId">
          <el-select v-model="form.couponId" placeholder="请选择满额送券券">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable size="small"
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item  label="选择商品" prop="targetsArray">
          <el-transfer
                  :titles="['未选','已选']"
                  filterable
                  :filter-method="filterMethod"
                  filter-placeholder="请输入商品名称"
                  v-model="selectedGoods"
                  :data="goodsList"
                   @change="handleChange"
                  :props="{
                        key: 'id',
                        label: 'name'
                      }">
                </el-transfer>
        </el-form-item>
        <el-form-item label="图片地址" prop="imgUrl">
          <el-upload class="avatar-uploader" accept="image/jpeg,image/png" action="oss-cn-beijing.aliyuncs.com"
                     :show-file-list="false" :auto-upload="true" :http-request="uploadPic" :on-success="handleAvatarSuccess" :before-upload="beforePicUpload">
                     <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                   </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import oss from '../../../utils/oss.js'
    import {
      listGoods,
      queryUploadToken
    } from "@/api/youxuan/goods";
import { listPreferential, getPreferential, delPreferential, addPreferential, updatePreferential, exportPreferential } from "@/api/youxuan/preferential";

export default {
  name: "Preferential",
  components: {
  },
  data() {
    const generateData = _ => {
                  const goodsList = [];
                  listGoods().then(response => {
                     this.goodsList = response.rows;
                    });
                     return goodsList;
                };
    return {
      data: generateData(),
             selectedGoods: [],
             filterMethod(query, item) {
               return item.name.indexOf(query) > -1;
             },
      goodsList:[],
      show_0:false,
      show_1:false,
      show_2:false,
      show_3:false,
       tempUrl: '',
       uploadToken: '',
       imageUrl: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠管理表格数据
      preferentialList: [],
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 优惠类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        description: null,
        condition: null,
        reduction: null,
        seckillPrice: null,
        startTime: null,
        status:null,
        couponId: null,
        endTime: null,
        targetsArray: null,
        targets:null,
        gmtCreate: null,
        gmtUpdate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "优惠类型不能为空", trigger: "change" }
        ],
        description: [
          { required: true, message: "促销活动说明不能为空", trigger: "blur" }
        ],
        targetsArray: [
          { required: true, message: "请选择商品", trigger: "blur" }
        ],

                  startTime: [{
                    required: true,
                    message: '请选择开始时间',
                    trigger: 'blur'
                  }, ],
                  endTime: [{
                    required: true,
                    message: '请选择结束时间',
                    trigger: 'blur'
                  }, ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("youxuan_acticity_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("youxuan_preferential_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
     queryToken() {
            queryUploadToken().then(response => {
              if (response.code == 200)
                this.uploadToken = response.data;
            });
          },
          handleChange(value, direction, movedKeys) {


                  if(movedKeys.length!=0)
                  {
                      if(direction=='right'){
                         console.log(this.selectedGoods);
                      }

                       else if(direction=='left'){

                      console.log(this.selectedGoods);
                    }

                  this.form.targetsArray = this.selectedGoods;
                  this.msgSuccess('操作成功！');
                  }
                      },
      handleAvatarSuccess(res, file) {
        console.log(res,file);
            this.imageUrl = this.tempUrl;
          },
          statusFormat(row, column) {
            return this.selectDictLabel(this.statusOptions, row.status);
          },
          beforePicUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isLt2M) {
              this.msgError('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
          },
                async uploadPic(option) { //上传OSS
                  let that = this;
                  oss.setToken(that.uploadToken);
                  oss.ossUploadFile(option).then(res => {
                    if (res != null) {
                      that.tempUrl = res.fullUrl;
                    }
                  });
                },
    /** 查询优惠管理列表 */
    getList() {
      this.loading = true;
      listPreferential(this.queryParams).then(response => {
        this.preferentialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 优惠类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        description: null,
        condition: null,
        reduction: null,
        seckillPrice: null,
        startTime: null,
        couponId: null,
        endTime: null,
        targetsArray: null,
        targets:null,
        imgUrl: null,
        gmtCreate: null,
        gmtUpdate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
       this.queryToken();
      this.reset();
      this.open = true;
      this.title = "添加优惠管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
       this.queryToken();
      this.reset();

      const id = row.id || this.ids
      getPreferential(id).then(response => {
        this.form = response.data;
        if( this.form.targets!=null){
           var selectedList = this.form.targetsArray;
          for(var i=0;i<selectedList.length;i++){
            this.selectedGoods[i] = parseInt(selectedList[i]);
          }
          console.log("eee",this.selectedGoods);
        }

        this.form.type = parseInt(this.form.type);
        this.show_0=false;
        this.show_1=false;
        this.show_2=false;
        this.show_3=false;
        if(this.form.type == 0){
          this.show_0=true;
        }
        else if (this.form.type == 1){
          this.show_1=true;
        }
        else if (this.form.type == 2){
          this.show_2=true;
        }
        else if (this.form.type == 3){
          this.show_3=true;
        }
         this.imageUrl = this.form.imgUrl;
        this.open = true;
        this.title = "修改优惠管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
       this.form.imgUrl = this.imageUrl;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.order!=null)
            this.form.order=parseInt(this.form.order)
          if (this.form.id != null) {
            updatePreferential(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPreferential(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除优惠管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPreferential(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    changeType(val){
      this.show_0=false;
      this.show_1=false;
      this.show_2=false;
      this.show_3=false;
      if(val == 0){
        this.show_0=true;
      }
      else if (val == 1){
        this.show_1=true;
      }
      else if (val == 2){
        this.show_2=true;
      }
      else if (val == 3){
        this.show_3=true;
      }

    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPreferential(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
